from nmj.scanners.movie import NMJImage
from nmj.scanners.tmdb import TMDBMovie, to_unicode
from tmdb3 import set_key, set_locale, searchMovie
import logging

_LOGGER = logging.getLogger(__name__)

def to_nmj_images(images):
	result = []

	for image in images:
		try:
			url = image.geturl()
			_LOGGER.debug("to_nmj_images %s", url)
			result.append(NMJImage(url))
		except:
			pass
	else:
		_LOGGER.warning("No image to download")
	return result

class TMDb3Scanner(object):
	def __init__(self):
		set_key("104e67f6ef05585ed35eec68f5cae0bf")
		set_locale("fr", "fr")


	def to_nmj_movie(self, *web_results):
		results = []
		for movie in web_results:
			results.append(TMDBMovie(
				tmdb_id=movie.id,
				imdb_id=movie.imdb,
				title=movie.title,
				synopsis=movie.overview,
#				short_synopsis="",
				posters=to_nmj_images(movie.posters or [movie.poster,]),
				fanarts=to_nmj_images(movie.backdrops or [movie.backdrop,]),
				genres=[genre.name for genre in movie.genres],
				cast={"actor" : [{"name" : actor.name} for actor in movie.cast], "director" : [{"name" : person.name} for person in movie.crew if person.job == "Director"]},
				rating=movie.popularity,
			))
		return results

	def search(self, string, **_kwargs):
		try:
			movies = searchMovie(to_unicode(string))
			for movie in movies:
				movie.get_media = self.get_media(movie)
			return movies
		except:
			_LOGGER.exception("Failed to find data for movie %s", string)
			return []

	def get_media(self, movie, get_first_result=True):
		def fetch():
			results = self.to_nmj_movie(movie)
			if get_first_result:
				return results[0]
			else:
				return results
		return fetch

if __name__ == "__main__":
	import sys
	logging.basicConfig(format='%(asctime)-15s %(message)s', level=logging.DEBUG)

	scanner = TMDb3Scanner()
	result = scanner.search(" ".join(sys.argv[1:]))
	print result[0].genres
	print result[0].cast
	print result[0].crew
	_LOGGER.info("%s", result[0].get_media())


